package org.softee.extractor.sax.helper;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.softee.extractor.helper.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

public class DomBuilder implements ResultBuildingContentHandler<Document> {
    private static final Logger logger = new Logger(DomBuilder.class);

    private static DocumentBuilder documentBuilder;
    static {
        try {
             documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // handled in constructor
        }
    }

    private Document document;
    private Node context;
    private boolean withinCData;

    public DomBuilder() {
        if (documentBuilder == null) {
            throw new IllegalStateException("No DocumentBuilder");
        }
        log("new()");
    }

    @Override
    public Document getResult() {
        return document;
    }

    @Override
    public void startDocument() throws SAXException {
        log("startDocument()");
        document = documentBuilder.newDocument();
        this.context = document;

    }

    @Override
    public void endDocument() throws SAXException {
        log("endDocument()");
        // don't null the document, since it needs to be recoverable after endDocument()
        this.context = null;
    }

    @Override
    public void processingInstruction(String target, String data) {
        log("processingInstruction('%s', '%s')", target, data);

    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes atts) {
        log("startElement('%s', '%s', '%s')", uri, localName, qName);
        for (int i = 0; i < atts.getLength(); i++) {
            log("  attribute: %s='%s'", atts.getQName(i), atts.getValue(i));
        }
        // Create a new element
        Element element = document.createElementNS(uri, qName);
        int aCount = atts.getLength();
        for (int i = 0; i < aCount; i++) {
            element.setAttributeNS(atts.getURI(i), atts.getQName(i), atts.getValue(i));
        }
        // add it to the context
        context.appendChild(element);
        // and let the newly created element be the new context
        context = element;
    }

    @Override
    public void endElement(String uri, String localName, String qName) {
        log("endElement('%s', '%s', '%s')", uri, localName, qName);
        // move the context up to the parent
        Node parent = context.getParentNode();
        if (parent instanceof Element) {
            context = parent;
        } else {
            // we're back at the Document node
            context = null;
        }
    }


    @Override
    public void characters(char[] ch, int start, int length) {
        String value = new String(ch, start, length);
        log("characters('%s')", value);
        Node node = withinCData ? document.createCDATASection(value) : document.createTextNode(value);
        context.appendChild(node);
    }

    @Override
    public void ignorableWhitespace(char[] ch, int start, int length) {
        String value = new String(ch, start, length);
        log("ignorableWhitespace('%s')", value);
        context.appendChild(document.createTextNode(value));
    }

    @Override
    public void startPrefixMapping(String prefix, String uri) {
        log("startPrefixMapping('%s', '%s')", prefix, uri);
    }

    @Override
    public void endPrefixMapping(String prefix) {
        log("endPrefixMapping('%s')", prefix);
    }

    @Override
    public void setDocumentLocator(Locator locator) {
        log("setDocumentLocator('%s')", locator);

    }

    @Override
    public void skippedEntity(String name) {
        log("skippedEntity('%s')", name);

    }

    @Override
    public void comment(char[] ch, int start, int length) throws SAXException {
        String value = new String(ch, start, length);
        log("comment(%s)", value);
        context.appendChild(document.createComment(value));
    }

    @Override
    public void startCDATA() throws SAXException {
        log("startCDATA()");
        withinCData = true;
    }

    @Override
    public void endCDATA() throws SAXException {
        log("endCDATA()");
        withinCData = false;
    }

    @Override
    public void startDTD(String name, String publicId, String systemId)
            throws SAXException {
        log("startDTD(%s)", name);
    }

    @Override
    public void endDTD() throws SAXException {
        log("endDTD()");
    }

    @Override
    public void startEntity(String name) throws SAXException {
        log("startEntity(%s)", name);
    }

    @Override
    public void endEntity(String name) throws SAXException {
        log("endEntity(%s)", name);

    }

    private void log(String format, Object... args) {
        logger.log(format, args);
    }

}
